<?php
/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

/**
 * View that uses the Smarty engine.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package Simplify_Kernel_View
 */
class SmartyView extends View
{

  protected $smarty;

  /**
   * Constructor.
   *
   * @return void
   */
  public function __construct()
  {
    $this->smarty = new SmartyWrapper();

    $this->smarty->template_dir = SY_APP_PATH . '/home/';
    $this->smarty->compile_dir = SY_APP_PATH . '/cache/smarty/templates_c/';
    $this->smarty->config_dir = SY_APP_PATH . '/cache/smarty/configs/';
    $this->smarty->cache_dir = SY_APP_PATH . '/cache/smarty/cache/';

    $this->smarty->php_handling = SMARTY_PHP_ALLOW;
    $this->smarty->left_delimiter = '<{';
    $this->smarty->right_delimiter = '}>';

    $this->defaultLayout = 'default_smarty';
  }

  /**
   * (non-PHPdoc)
   * @see simplify2/kernel/view/IView#render($object)
   */
  public function render(IRenderable $object = null)
  {
    if (empty($object)) $object = $this;

    $template = $object->getTemplate();

    $output = $this->internalRender($object, $template);

    $layout = $object->getLayout();

    if ($layout !== false) {
      if (empty($layout)) $layout = $this->defaultLayout;

      $view = View::factory('Smarty');
      $view->copyAll($object);
      $view->set('layout_content', $output);
      $view->setTemplate('layouts/' . $layout);
      $view->setLayout(false);
      $output = $view->render(null, View::RENDER_VAR);
    }

    return $output;
  }

  /**
   * Render the view.
   *
   * @param $object
   * @param $template
   * @return unknown_type
   */
  protected function internalRender($object, $template)
  {
    $this->response->header('Content-Type: text/html; charset=UTF-8');

    foreach ($object->getAll() as $name => $value) {
      $this->smarty->assign_by_ref($name, $value);
    }

    $this->smarty->assign_by_ref('view', $this->smarty);

    return $this->smarty->fetch($template);
  }
}

?>